﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace NuMvvm.Commands
{
    /// <summary>
    /// Relay command. 
    /// Based on source: http://wpftutorial.net/DelegateCommand.html
    /// </summary>
    public class DelegateCommand<T> : ICommand<T>
    {
        private readonly Func<T, bool> _canExecute;
        private readonly Action<T> _execute;


        public DelegateCommand(Action<T> execute)
        {
            _execute = execute;
            _canExecute = null;
        }

        public DelegateCommand(Action<T> execute,
                               Func<T, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
        }

        public void Execute(T parameter)
        {
            _execute(parameter);
        }

        public bool CanExecute(T parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

        #region Implements ICommand 


        public event EventHandler CanExecuteChanged;

        bool ICommand.CanExecute(object parameter)
        {
            return CanExecute((T)parameter);
        }

        void ICommand.Execute(object parameter)
        {
            Execute((T)parameter);
        }

        #endregion
    }
}
